package com.atguigu.gmall.payment.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author: atguigu
 * @create: 2023-03-13 15:44
 */
@RestController
@RequestMapping("/api/payment")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;


    /**
     * 展示支付宝支付表单页面
     *
     * @param orderId 订单ID
     * @return
     */
    @GetMapping("/alipay/submit/{orderId}")
    public String createAlipayForm(HttpServletRequest request, @PathVariable("orderId") Long orderId) {
        String userId = AuthContextHolder.getUserId(request);
        return alipayService.createAlipayForm(orderId, userId);
    }


    /**
     * 处理支付宝支付成功后同步回调,将地址重定向到渲染支付成功html页面请求地址
     * @param response
     * @throws IOException
     */
    @GetMapping("/alipay/callback/return")
    public void redirectUrl(HttpServletResponse response) throws IOException {
        response.sendRedirect(AlipayConfig.return_order_url);
    }


    /**
     * 支付宝进行异步回调,通知商家支付结果,修改本地交易记录状态
     * @param paramsMap 支付宝回调提交所有参数 通过get方法key获取对于值
     * @return
     */
    @PostMapping("/alipay/callback/notify")
    public String notifyPayResult(@RequestParam Map<String, String> paramsMap){
        return alipayService.notifyPayResult(paramsMap);
    }


    /**
     * 发起退款
     * @param orderId
     * @return
     */
    @GetMapping("refund/{orderId}")
    public Result refund(@PathVariable(value = "orderId")Long orderId) {
        // 调用退款接口
        boolean flag = alipayService.refund(orderId);
        return Result.ok(flag);
    }
}
